package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.CollectionService;
import com.heima.common.redis.BehaviorConstants;
import com.heima.model.article.dto.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CollectionServiceImpl implements CollectionService {
    /**
     * 收藏功能
     *
     * @param dto
     * @return
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public ResponseResult Collection(CollectionBehaviorDto dto) {
        //判断数据
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        HashOperations hashOperations = redisTemplate.opsForHash();
        log.info("接收到的参数：{}", dto);
        //1.0判断登录
        if (ApThreadLocalUtil.getApUser() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getOperation() == 0) {
            //判断是否是重复收藏
            Object o = hashOperations.get(ApThreadLocalUtil.getApUser().getId().toString(), BehaviorConstants.COLLECTION_BEHAVIOR+dto.getEntryId());

            if (o != null ) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已经收藏过了");
            }else {
                hashOperations.put(ApThreadLocalUtil.getApUser().getId().toString(),
                        BehaviorConstants.COLLECTION_BEHAVIOR+dto.getEntryId(), JSON.toJSONString(dto));

            }

        } else{
            //取消收藏
           // redisTemplate.delete(BehaviorConstants.COLLECTION_BEHAVIOR+dto.getEntryId());
           // redisTemplate.delete(ApThreadLocalUtil.getApUser().toString());
            hashOperations.delete(ApThreadLocalUtil.getApUser().getId().toString(),BehaviorConstants.COLLECTION_BEHAVIOR+dto.getEntryId());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
